let config = require("../../../config/config.js");
var QQMapWx = require("../../../utils/qqmap-wx-jssdk.js");
var qqmapsdk = new QQMapWx({ key: config.map_key });
let request = require("../../../utils/request.js"); //封装的request请求
const app = getApp(); //获取应用实例
let flag = true;

Component({
  /**
   * 组件的属性列表
   */
  properties: {
    city: String,
    longitude: Number,
    latitude: Number,
  },

  /**
   * 组件的初始数据
   */
  data: {
    searchAddress: "",
    isCanNext: true,
  },

  /**
   * 组件的方法列表
   */
  methods: {
    /**
     * 获取搜索输入框的文字
     */
    getSearch(event) {
      let _this = this;
      this.setData({ searchAddress: event.detail.value });
      qqmapsdk.getSuggestion({
        keyword: event.detail.value,
        region: this.data.city,
        page_size: 20,
        success(res) {
          console.log("地图搜索：", res);
          _this.setData({
            searching: res.data,
            searchResult: [],
          });
        },
      });
    },
    /**
     * 搜索到的目位置
     */
    showSearchMapMark(e) {
      let type = e.currentTarget.dataset.type;
      let index = e.currentTarget.dataset.index;
      let record = {};
      let searching;
      if (type == "park") {
        searching = this.data.searchPark;
        record = {
          place: searching[index].parkName,
          latitude: searching[index].latitude,
          longitude: searching[index].longitude,
          address: searching[index].parkAddress,
        };
      } else if (type == "address") {
        searching = this.data.searching;
        record = {
          place: searching[index].title,
          latitude: searching[index].location.lat,
          longitude: searching[index].location.lng,
          address: searching[index].address,
        };
      }
      var searcheRecord = wx.getStorageSync("searcheRecord");
      if (Array.isArray(searcheRecord)) {
        if (searcheRecord.length == 2) {
          searcheRecord.splice(1, 1);
          searcheRecord.unshift(record);
        } else {
          searcheRecord.unshift(record);
        }
      } else {
        searcheRecord = [];
        searcheRecord.push(record);
      }
      wx.setStorageSync("searcheRecord", searcheRecord);
      this.getNearbyPark(record.longitude, record.latitude);
      this.setData({ searching: [] });
      this.triggerEvent("search", record);
    },
    /**
     * 获取附近停车点
     * @param {Number} longitude 经度
     * @param {Number} latitude 纬度
     */
    getNearbyPark(longitude, latitude) {
      let _this = this;
      let parmas = {
        longitude: longitude,
        latitude: latitude,
        currentPage: 1,
        pageSize: 10,
      };
      request
        .http("/park/info/getNearbyParkList", "GET", parmas)
        .then((res) => {
          console.log(res.data);
          if (res.data.code == 200) {
            let parkList = res.data.data.records;
            let locationList = [];
            for (var i = 0; i < parkList.length; i++) {
              locationList.push({
                longitude: parkList[i].longitude,
                latitude: parkList[i].latitude,
              });
            }
            this.calculateDistance(
              { longitude: this.data.longitude, latitude: this.data.latitude },
              locationList,
              function (res) {
                console.log(res);
                let data = res;
                if (data.status == 0) {
                  for (var i = 0; i < parkList.length; i++) {
                    let distances = data.result.elements[i].distance;
                    parkList[i].distances = (distances / 1000).toFixed(2);
                    console.log(parkList[i].distances);
                    if (parkList[i].parkImgUrl) {
                      let index = parkList[i].parkImgUrl
                        .split(",")[0]
                        .lastIndexOf(".");
                      let name = parkList[i].parkImgUrl
                        .split(",")[0]
                        .substr(0, index);
                      let ext = parkList[i].parkImgUrl
                        .split(",")[0]
                        .substr(index + 1); // parkList[i].parkImgUrl = name + '@_@350.' + ext
                      parkList[i].parkImgUrl = name + "." + ext;
                    }
                  }
                  _this.setData({ searchResult: parkList });
                  console.log(_this.data.searchResult);
                }
              }
            );
            if (parkList.length <= 0) {
              wx.showToast({
                title: "当前地点附近暂无停车场可用",
                icon: "none",
              });
            }
          }
        });
    },
    /**
     * 触底加载
     */
    scrollTolower() {
      console.log("滑动加载");
      if (!flag) {
        return;
      }
      flag = false;
      this.setData({ page: this.data.page + 1 });
      this.getNearbyPark(this.data.longitude, this.data.latitude);
    },
    /**
     * 跳转到购买月租卡页面
     */
    toBuyCard(e) {
      let parkData = e.currentTarget.dataset.park;
      if (wx.getStorageSync("token")) {
        wx.navigateTo({
          url:
            "/pages/pay/monthly/monthly?parkData=" + JSON.stringify(parkData),
        });
      } else {
        //  获取用户信息
        this.getUserProfile(
          "/pages/pay/monthly/monthly?parkData=" + JSON.stringify(parkData)
        );
      }
    },
    /**
     * 跳转到夜间卡页面
     */
    toReceiveMabi(e) {
      let parkData = e.currentTarget.dataset.park;
      if (wx.getStorageSync("token")) {
        wx.navigateTo({
          url:
            "../pay/nightCard/nightCard?parkData=" +
            encodeURIComponent(JSON.stringify(parkData)),
        });
      } else {
        //  获取用户信息
        this.getUserProfile(
          "../pay/nightCard/nightCard?parkData=" +
            encodeURIComponent(JSON.stringify(parkData))
        );
      }
    },
    //点击打开停车场信息
    checkMarkerPark(e) {
      let item = e.currentTarget.dataset.val;
      this.triggerEvent("myevent", item);
    },

    /**
     * 在地图中打开
     */
    toMapNavigation(e) {
      let index = e.currentTarget.dataset.index;
      let parkData = this.data.searchResult[index];
      let latitude = Number(parkData.latitude);
      let longitude = Number(parkData.longitude);
      wx.openLocation({
        latitude,
        longitude,
        name: parkData.parkName,
        address: parkData.parkAddress,
        scale: 14,
      });
    },

    lookDetail() {
      console.log("跳转");
    },

    /**
     * 跳转到预约页面
     */
    toReserve(e) {
      console.log("跳转到预约页面：", e);

      if (e.currentTarget.dataset.park.reserveParkSpace == 0) {
        wx.showToast({
          title: "当前可预约车位为0，请选择其他停车场",
          icon: "none",
        });
        return;
      }

      if (wx.getStorageSync("token")) {
        wx.navigateTo({
          url:
            "/pages/subscribe/subscribe?parkId=" +
            e.currentTarget.dataset.park.id +
            "&parkName=" +
            e.currentTarget.dataset.park.parkName,
        });
      } else {
        //  获取用户信息
        this.getUserProfile(
          "/pages/subscribe/subscribe?parkId=" +
            e.currentTarget.dataset.park.id +
            "&parkName=" +
            e.currentTarget.dataset.park.parkName
        );
      }
    },
    /**
     * 跳转到领取停车券页面：
     */
    toReceiveTicket(e) {
      console.log("跳转到领取停车券页面：", e);
      if (wx.getStorageSync("token")) {
        wx.navigateTo({
          url:
            "/pages/park-ticket/parkTicket?parkId=" +
            e.currentTarget.dataset.park.id,
        });
      } else {
        //  获取用户信息
        this.getUserProfile(
          "/pages/park-ticket/parkTicket?parkId=" +
            e.currentTarget.dataset.park.id
        );
      }
    },
    /**
     * 计算两点之间距离
     * @param {Object} from 起始位置经纬度
     * @param {Array} to 终点位置经纬度
     * @param {Function} callback 回调函数
     */
    calculateDistance(from, to, callback) {
      console.log("计算两点之间距离", from, to);

      if (to.length <= 0) {
        return;
      }
      qqmapsdk.calculateDistance({
        mode: "driving",
        from,
        to,
        success(res) {
          callback(res);
        },
        fail: function (error) {
          console.error(error);
        },
      });
    },
    /**
     * 关闭弹窗
     */
    bottomPopClose() {
      this.triggerEvent("bottomPopClose");
    },
    /**
     * 授权
     */
    getUserProfile(e) {
      this.triggerEvent("getUserProfile", e);
    },
  },
});
